package com.qidian.study.servlets;

import com.qidian.study.util.JsonTools;
import com.qidian.study.util.pojo.VideoResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author 戴着假发的程序员
 * @company 起点编程
 */
@WebServlet("/fileupload")
public class FileUploadServlet extends HttpServlet {
    private String targetDir = "E:\\resources";
    private List<String> imageExt = new ArrayList<>(Arrays.asList(".jpg",".png",".jpeg",".gif"));
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理跨域
        // 允许跨域请求的设置
        /* 允许跨域请求的域名（站点） */
        response.setHeader("Access-Control-Allow-Origin", "*");
        /* 允许跨域的请求方法GET, POST, HEAD 等 */
        response.setHeader("Access-Control-Allow-Methods", "*");
        /* 重新预检验跨域的缓存时间 (s) */
        response.setHeader("Access-Control-Max-Age", "3600");
        /* 允许跨域的请求头 */
        response.setHeader("Access-Control-Allow-Headers", "*");
        /* 是否携带cookie */
        response.setHeader("Access-Control-Allow-Credentials", "true");


        // 创建DiskFileItemFactory  这个Factory就是用来配置文件上传处理器的
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 配置一个临时仓库(就是存储临时文件的目录)
        ServletContext servletContext = this.getServletConfig().getServletContext();
        File repository = new File(servletContext.getRealPath("/")+"temp");
        if(!repository.exists() || !repository.isDirectory()){
            repository.mkdir();
        }
        // 设置仓库
        factory.setRepository(repository);
        // 设置字符集
        factory.setDefaultCharset("utf-8");
        // 创建一个新的文件上传处理器
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            // 解析Request，得到一个items列表，里面是FileItem
            // 这里的FileItem表示一个表单域
            List<FileItem> items = upload.parseRequest(request);
            // 遍历集合
            Iterator<FileItem> iter = items.iterator();
            if (iter.hasNext()) {
                // 每次获取一个FileItem出来
                FileItem item = iter.next();
                if (!item.isFormField())  {
                    System.out.println("-----文件域-----");
                    // 文件域
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();
                    System.out.println("域名:"+fieldName);
                    System.out.println("文件名："+fileName);
                    System.out.println("文件类型："+contentType);
                    System.out.println("文件大小："+sizeInBytes);
                    // 创建目标文件
                    File target = null;
                    // 获取后缀
                    String ext = fileName.substring(fileName.lastIndexOf("."));
                    // 文件名
                    String fname = UUID.randomUUID().toString().replace("-","")+(new Random().nextInt(900)+100);
                    String fileUrl = null;
                    if(imageExt.contains(ext)){
                        // 图片
                        target = new File(targetDir+"\\image\\"+fname+ext);
                        fileUrl = "http://localhost:8888/image/"+fname+ext;
                    }else if (ext.equals(".mp4") || ext.equals(".ogg")){
                        // 视频
                        target = new File(targetDir+"\\video\\"+fname+ext);
                        fileUrl = "http://localhost:8888/video/"+fname+ext;
                    }
                    if(target!=null) {
                        item.write(target);
                        // 返回文件的访问地址
                        response.getWriter().write(JsonTools.object2json(VideoResponse.ok(fileUrl)));
                    }else{
                        response.getWriter().write(JsonTools.object2json(VideoResponse.error(500,"文件格式不正确")));
                    }

                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
